package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

public class ZipUtils {	

	public static void main(String[] args) {
		try {
			new ZipUtils().zipFile("E:/zip22.zip", new String[] { "E:/彩票.txt","E:/重装系统之后启动mysql.txt" }, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 把文件或文件夹压缩到指定的流中
	 * @param zout 压缩流
	 * @param beZipedFile 被压缩的文件或文件夹
	 * @param basePath 被压缩的文件的父目录
	 * @throws IOException
	 */
	public void zipFile(ZipOutputStream zout, File beZipedFile,String basePath) throws IOException {
		if (beZipedFile.isDirectory()) {
			File[] fileList = beZipedFile.listFiles();
			if (basePath.length() > 0) {
				basePath = basePath + "/";
			}
			for (File file : fileList) {
				zipFile(zout, file, basePath + beZipedFile.getName());
			}
		} else {
			if (basePath.length() > 0) {
				basePath = basePath + "/";
			}
			zout.putNextEntry(new ZipEntry(basePath + beZipedFile.getName()));
			InputStream is=new FileInputStream(beZipedFile);
			IOUtils.copy(is, zout);//这个效率真高，比直接从流中读取要快得多
			is.close();
			zout.closeEntry();
		}
	}

	/**
	 * 将指定的被压缩文件压缩到指定的文件中
	 * 
	 * @param zipFilePath 要生成的压缩包的文件名
	 * @param beZipedFilePath 要压缩的文件名或目录名数组
	 * @param createNew 是否生成新的压缩文件
	 * @throws IOException
	 */
	public void zipFile(String zipFilePath, String beZipedFilePath[],boolean createNew) throws IOException {
		File zipFile = new File(zipFilePath);
		if ( !zipFile.exists() || (createNew && zipFile.delete()) ){
			zipFile.getParentFile().mkdirs();
			zipFile.createNewFile();
		}
		OutputStream out=new FileOutputStream(zipFile);
		ZipOutputStream zout = new ZipOutputStream(out);
		for (String filePath : beZipedFilePath) {
			File file = new File(filePath);
			if (!file.exists()) {
				System.out.println(file.getAbsoluteFile() + " is not exists");
				continue;
			}
			zipFile(zout, file, "");
		}
		zout.flush();
		zout.close();		
		out.close();
	}
	public void unZipFile(String beUnZipedFiledPath,String outFilePath,boolean replace) throws IOException{
		File outFile=new File(outFilePath);
		if(!replace && outFile.exists()){
			
		}
		ZipFile zipFile=new ZipFile(beUnZipedFiledPath);
		Enumeration<? extends ZipEntry> elements=zipFile.entries();
		while(elements.hasMoreElements()){
			ZipEntry zipEntry=elements.nextElement();
			if(zipEntry.isDirectory()){
				
			}
			
		}
	}
}